package com.easemob.chat.core;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build.VERSION;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import com.easemob.analytics.EMLoginCollector;
import com.easemob.analytics.EMTimeTag;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatConfig;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EMAuthenticationException;
import com.easemob.exceptions.EMNetworkUnconnectedException;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.easemob.util.NetUtils;
import com.xonami.javaBells.JingleManager;
import java.io.File;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Random;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.PrivacyListManager;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smack.provider.PrivacyProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smackx.GroupChatInvitation.Provider;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.entitycaps.EntityCapsManager;
import org.jivesoftware.smackx.packet.ChatStateExtension.Provider;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.OfflineMessageInfo.Provider;
import org.jivesoftware.smackx.packet.OfflineMessageRequest.Provider;
import org.jivesoftware.smackx.provider.DataFormProvider;
import org.jivesoftware.smackx.provider.DelayInfoProvider;
import org.jivesoftware.smackx.provider.DiscoverInfoProvider;
import org.jivesoftware.smackx.provider.DiscoverItemsProvider;
import org.jivesoftware.smackx.provider.MUCAdminProvider;
import org.jivesoftware.smackx.provider.MUCOwnerProvider;
import org.jivesoftware.smackx.provider.MUCUserProvider;
import org.jivesoftware.smackx.provider.VCardProvider;

public class XmppConnectionManager
{
  private static final String TAG = XmppConnectionManager.class.getSimpleName();
  private static final String PERF = "perf";
  private static final String RESOURCE = "mobile";
  private static String xmppResource = null;
  private String bareJid;
  private String password;
  private Context context;
  private final PingListener pingListener = new PingListener(null);
  private XMPPConnection connection;
  private ConnectionConfiguration connectionConfig;
  private final XmppConnectionListener connectionListener = new XmppConnectionListener(null);
  private l chatConnectionListener = null;
  private static XmppConnectionManager instance = null;
  private int randomBase = -1;
  private int attempts = 0;
  private Thread reconnectionThread = null;
  f.c currentHost = null;
  boolean enableWakeLock = false;
  PowerManager.WakeLock wakeLock = null;
  private static final String LOCK = "easemoblock";
  boolean isDone = false;
  boolean isConnectivityRegistered = false;
  private EMTimeTag chatTag;
  private EMTimeTag imTag;
  private BroadcastReceiver connectivityBroadcastReceiver = new BroadcastReceiver()
  {
    public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent)
    {
      String str = paramAnonymousIntent.getAction();
      if (!str.equals("android.net.conn.CONNECTIVITY_CHANGE"))
      {
        EMLog.d(XmppConnectionManager.TAG, "skip no connectivity action");
        return;
      }
      EMLog.d(XmppConnectionManager.TAG, "connectivity receiver onReceiver");
      int i = NetUtils.hasDataConnection(paramAnonymousContext) ? 0 : 1;
      if (i != 0)
      {
        if (((XmppConnectionManager.this.reconnectionThread == null) || (!XmppConnectionManager.this.reconnectionThread.isAlive())) && (XmppConnectionManager.this.isConnected()))
          new Thread()
          {
            public void run()
            {
              XmppConnectionManager.this.reConnect();
            }
          }
          .start();
      }
      else
      {
        if (paramAnonymousContext == null)
          return;
        if (!NetUtils.hasDataConnection(paramAnonymousContext))
        {
          EMLog.d(XmppConnectionManager.TAG, "in connectivity broadcast, skip since no data connection");
          return;
        }
        if (!XmppConnectionManager.this.isConnected())
        {
          XmppConnectionManager.this.resetAttempts();
          if (XmppConnectionManager.this.reconnectionThread != null)
          {
            XmppConnectionManager.this.reconnectionThread.interrupt();
            new Thread()
            {
              public void run()
              {
                XmppConnectionManager.this.startReconnectionThread();
              }
            }
            .start();
          }
        }
      }
    }
  };

  public void onInit()
  {
    this.context = EMChat.getInstance().getAppContext();
    initConnectionConfig();
    this.connection = new XMPPConnection(this.connectionConfig);
    EntityCapsManager.getInstanceFor(this.connection).disableEntityCaps();
    this.isDone = false;
  }

  public void onInit(String paramString1, String paramString2)
  {
    onInit();
    this.bareJid = paramString1;
    this.password = paramString2;
  }

  public void setChatTag(EMTimeTag paramEMTimeTag)
  {
    this.chatTag = paramEMTimeTag;
  }

  public String getCurrentUser()
  {
    return EMContactManager.getUserNameFromEid(this.bareJid);
  }

  public String getCurrentPwd()
  {
    return this.password;
  }

  private void initConnectionConfig()
  {
    configure(ProviderManager.getInstance());
    if (this.connectionConfig == null)
    {
      Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
      SASLAuthentication.supportSASLMechanism("PLAIN");
      XMPPConnection.DEBUG_ENABLED = EMChatConfig.debugMode;
      SmackConfiguration.setPacketReplyTimeout(60000);
      this.currentHost = f.a().b();
      this.connectionConfig = new ConnectionConfiguration(this.currentHost.a, this.currentHost.b, EMChatConfig.getInstance().getDomain());
      this.connectionConfig.setRosterLoadedAtLogin(false);
      this.connectionConfig.setSendPresence(false);
      this.connectionConfig.setReconnectionAllowed(false);
      this.connectionConfig.setCompressionEnabled(true);
      if (Build.VERSION.SDK_INT >= 14)
      {
        this.connectionConfig.setTruststoreType("AndroidCAStore");
        this.connectionConfig.setTruststorePassword(null);
        this.connectionConfig.setTruststorePath(null);
      }
      else
      {
        this.connectionConfig.setTruststoreType("BKS");
        String str = System.getProperty("javax.net.ssl.trustStore");
        if (str == null)
          str = System.getProperty("java.home") + File.separator + "etc" + File.separator + "security" + File.separator + "cacerts.bks";
        this.connectionConfig.setTruststorePath(str);
      }
    }
  }

  public void setChatConnectionListener(l paraml)
  {
    this.chatConnectionListener = paraml;
  }

  public void connect()
    throws EMNetworkUnconnectedException
  {
    EMLog.d(TAG, "connection manager:connect");
    if (this.connection == null)
    {
      EMLog.e(TAG, "fail to setup connection");
      throw new EMNetworkUnconnectedException("fail to setup connection");
    }
    if (this.connection.isConnected())
    {
      EMLog.d(TAG, "connection is connected, skip reconnect");
      return;
    }
    try
    {
      EMLog.d(TAG, "before connect");
      this.connection.connect();
      EMLog.d(TAG, "after connect");
    }
    catch (UnknownHostException localUnknownHostException)
    {
      EMLog.e(TAG, "unknow host exception:" + localUnknownHostException.toString());
      if (!NetUtils.hasNetwork(this.context))
        throw new EMNetworkUnconnectedException("no network available");
      throw new EMNetworkUnconnectedException(localUnknownHostException.getMessage());
    }
    catch (NoRouteToHostException localNoRouteToHostException)
    {
      EMLog.e(TAG, "NoRouteToHostException:" + localNoRouteToHostException.toString());
      throw new EMNetworkUnconnectedException(localNoRouteToHostException.getMessage());
    }
    catch (ConnectException localConnectException)
    {
      str = localConnectException.toString();
      EMLog.e(TAG, "ConnectException:" + str);
      if ((k.a().c()) && (str != null) && (str.toLowerCase().contains("refused")))
      {
        localc = f.a().f();
        if (localc != null)
          this.currentHost = localc;
        this.connection.getConfiguration().initHostAddresses(this.currentHost.a, this.currentHost.b);
      }
      throw new EMNetworkUnconnectedException(str);
    }
    catch (SocketException localSocketException)
    {
      EMLog.e(TAG, "SocketException:" + localSocketException.toString());
      throw new EMNetworkUnconnectedException(localSocketException.getMessage());
    }
    catch (SocketTimeoutException localSocketTimeoutException)
    {
      EMLog.e(TAG, "SocketTimeoutException:" + localSocketTimeoutException.toString());
      throw new EMNetworkUnconnectedException(localSocketTimeoutException.getMessage());
    }
    catch (Exception localException)
    {
      f.c localc;
      localException.printStackTrace();
      String str = null;
      if (!"".equals(localException.getMessage()))
        str = localException.getMessage();
      else
        str = localException.toString();
      if ((k.a().c()) && (str != null) && (str.toLowerCase().contains("refused")) && (NetUtils.hasNetwork(this.context)))
      {
        localc = f.a().f();
        if (localc != null)
          this.currentHost = localc;
        this.connection.getConfiguration().initHostAddresses(this.currentHost.a, this.currentHost.b);
      }
      EMLog.e(TAG, "connection.connect() failed: " + str);
      throw new EMNetworkUnconnectedException(str);
    }
  }

  private void initConnection()
    throws EMNetworkUnconnectedException
  {
    EMLog.d(TAG, "enter initConnection()");
    if (!this.connection.isConnected())
    {
      EMLog.e(TAG, "Connection is not connected as expected");
      throw new EMNetworkUnconnectedException("Connection is not connected as expected");
    }
    this.connection.addConnectionListener(this.connectionListener);
    initFeatures();
    PacketTypeFilter localPacketTypeFilter = new PacketTypeFilter(com.easemob.chat.a.a.a.class);
    this.connection.addPacketListener(this.pingListener, localPacketTypeFilter);
  }

  private synchronized void login()
    throws EaseMobException
  {
    long l = System.currentTimeMillis();
    try
    {
      if (this.connection.isAuthenticated())
      {
        EMLog.d(TAG, "already login. skip");
        return;
      }
      if (!this.connection.isConnected())
      {
        EMLog.e(TAG, "Connection is not connected as expected");
        throw new EMNetworkUnconnectedException("Connection is not connected as expected");
      }
      EMLog.d(TAG, "try to login with barejid" + this.bareJid);
      this.connection.login(this.bareJid, this.password, getXmppResource(this.context));
      EMLog.d(TAG, "login successfully");
      PowerManager localPowerManager = (PowerManager)this.context.getSystemService("power");
      if ((this.wakeLock == null) && (this.enableWakeLock))
      {
        this.wakeLock = localPowerManager.newWakeLock(1, "easemoblock");
        this.wakeLock.acquire();
        EMLog.d(TAG, "acquire lock");
      }
    }
    catch (IllegalStateException localIllegalStateException)
    {
      EMLog.d(TAG, "illegalState in connection.login:" + localIllegalStateException.toString());
      if (localIllegalStateException.toString().indexOf(" Already logged in to server") < 0)
        throw new EaseMobException(localIllegalStateException.toString());
    }
    catch (Exception localException1)
    {
      EMLog.e(TAG, "Failed to login to xmpp server. Caused by: " + localException1.getMessage());
      String str1 = "401";
      String str2 = "not-authorized";
      String str3 = "SASL authentication failed using mechanism PLAIN";
      String str4 = localException1.getMessage();
      if ((str4 != null) && (str4.contains(str1)))
        throw new EMAuthenticationException(str1);
      if ((str4 != null) && (str4.contains(str2)))
        throw new EMAuthenticationException(str2);
      if ((str4 != null) && (str4.contains(str3)))
        throw new EMAuthenticationException(str3);
      throw new EaseMobException(str4);
    }
    try
    {
      sendVersionIQ();
      Presence localPresence = new Presence(Presence.Type.available);
      if (this.imTag != null)
      {
        localPresence.setImLoginTime(this.imTag.stop());
        this.imTag = null;
      }
      if (this.chatTag != null)
      {
        localPresence.setChatLoginTime(this.chatTag.stop());
        this.chatTag = null;
      }
      this.connection.sendPacket(localPresence);
      EMLog.d("perf", "[perf] login time(ms)" + (System.currentTimeMillis() - l));
      if (EMChatConfig.isDebugTrafficMode())
        com.easemob.b.a.d();
    }
    catch (Exception localException2)
    {
      localException2.printStackTrace();
    }
  }

  private void sendVersionIQ()
  {
    EMLog.d(TAG, "send version iq");
    s locals = new s(EMChat.getInstance().getVersion());
    locals.setTo(EMChatConfig.getInstance().getDomain());
    String str = EMChatConfig.getInstance().APPKEY + "_" + EMChatManager.getInstance().getCurrentUser() + "@" + EMChatConfig.getInstance().getDomain();
    locals.setFrom(str);
    this.connection.sendPacket(locals);
  }

  public void reuse()
  {
    this.isDone = false;
    this.connection.addConnectionListener(this.connectionListener);
  }

  public synchronized void connectSync(boolean paramBoolean)
    throws EaseMobException
  {
    if (this.isDone)
      return;
    EMLog.d(TAG, "enter connectSync");
    if ((this.connection.isConnected()) && (this.connection.isAuthenticated()))
      return;
    try
    {
      EMTimeTag localEMTimeTag = new EMTimeTag();
      localEMTimeTag.start();
      this.imTag = localEMTimeTag;
      connect();
      initConnection();
      login();
      EMLoginCollector.collectIMLoginTime(localEMTimeTag.stop());
      if (this.chatConnectionListener != null)
        this.chatConnectionListener.onConnectionSuccessful();
      resetAttempts();
    }
    catch (EaseMobException localEaseMobException)
    {
      String str = localEaseMobException.getMessage();
      EMLog.e(TAG, "connectSync with error = " + str);
      if ((!paramBoolean) && (!(localEaseMobException instanceof EMAuthenticationException)))
      {
        reConnect();
      }
      else
      {
        f.a().i();
        disconnect();
      }
      EMLoginCollector.collectConnectionError(localEaseMobException.getMessage());
      throw localEaseMobException;
    }
  }

  private synchronized void reConnect()
  {
    EMLog.d(TAG, "enter reConnect");
    this.connection.disconnect();
    if (!this.isDone)
    {
      registerConnectivityReceiver();
      startReconnectionThread();
    }
  }

  public void forceReconnect()
  {
    reConnect();
  }

  public void reconnectSync()
    throws EaseMobException
  {
    if (this.isDone)
      return;
    EMLog.d(TAG, "try to reconnectSync");
    connectSync(false);
  }

  public void reconnectASync()
  {
    if (this.isDone)
      return;
    EMLog.d(TAG, "try to reconnectASync");
    Thread local2 = new Thread()
    {
      public void run()
      {
        try
        {
          XmppConnectionManager.this.reconnectSync();
        }
        catch (Exception localException)
        {
          localException.printStackTrace();
        }
      }
    };
    local2.start();
  }

  public boolean disconnect()
  {
    try
    {
      EMLog.d(TAG, hashCode() + " : enter disconnect()");
      this.isDone = true;
      if (this.reconnectionThread != null)
        this.reconnectionThread.interrupt();
      unregisterConnectivityReceiver();
      if (this.connection != null)
      {
        if (this.connectionListener != null)
          this.connection.removeConnectionListener(this.connectionListener);
        EMLog.d(TAG, "trying to disconnect connection （" + this.connection.hashCode() + ")");
        this.connection.disconnect();
      }
      if (this.wakeLock != null)
        this.wakeLock.release();
      return true;
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
    return false;
  }

  public XMPPConnection getConnection()
  {
    return this.connection;
  }

  public boolean isAuthentificated()
  {
    if (this.connection == null)
      return false;
    return this.connection.isAuthenticated();
  }

  public boolean isConnected()
  {
    if (this.connection == null)
      return false;
    return this.connection.isConnected();
  }

  private void initFeatures()
  {
    ServiceDiscoveryManager localServiceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(this.connection);
    if (localServiceDiscoveryManager == null)
      localServiceDiscoveryManager = new ServiceDiscoveryManager(this.connection);
    localServiceDiscoveryManager.setIdentityName("EaseMob");
    localServiceDiscoveryManager.setIdentityType("phone");
    localServiceDiscoveryManager.addFeature("http://jabber.org/protocol/disco#info");
    localServiceDiscoveryManager.addFeature("jabber:iq:privacy");
    localServiceDiscoveryManager.addFeature("urn:xmpp:avatar:metadata");
    localServiceDiscoveryManager.addFeature("urn:xmpp:avatar:metadata+notify");
    localServiceDiscoveryManager.addFeature("urn:xmpp:avatar:data");
    localServiceDiscoveryManager.addFeature("http://jabber.org/protocol/nick");
    localServiceDiscoveryManager.addFeature("http://jabber.org/protocol/nick+notify");
    localServiceDiscoveryManager.addFeature("http://jabber.org/protocol/muc");
    localServiceDiscoveryManager.addFeature("http://jabber.org/protocol/muc#rooms");
    localServiceDiscoveryManager.addFeature("urn:xmpp:ping");
    localServiceDiscoveryManager.addFeature("http://jabber.org/protocol/disco#info");
    localServiceDiscoveryManager.addFeature("urn:xmpp:jingle:1");
    localServiceDiscoveryManager.addFeature("urn:xmpp:jingle:transports:ice-udp:1");
    localServiceDiscoveryManager.addFeature("urn:xmpp:jingle:apps:rtp:1");
    localServiceDiscoveryManager.addFeature("urn:xmpp:jingle:apps:rtp:audio");
    localServiceDiscoveryManager.addFeature("urn:xmpp:jingle:apps:rtp:video");
  }

  private void discoverServerFeatures()
  {
    try
    {
      ServiceDiscoveryManager localServiceDiscoveryManager = ServiceDiscoveryManager.getInstanceFor(this.connection);
      DiscoverInfo localDiscoverInfo = localServiceDiscoveryManager.discoverInfo(this.connection.getServiceName());
    }
    catch (XMPPException localXMPPException)
    {
      EMLog.w(TAG, "Unable to discover server features", localXMPPException);
    }
  }

  private void configure(ProviderManager paramProviderManager)
  {
    EMLog.d(TAG, "configure");
    try
    {
      if (Class.forName("com.xonami.javaBells.JingleManager") != null)
        JingleManager.enableJingle();
    }
    catch (Throwable localThrowable)
    {
    }
    paramProviderManager.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
    paramProviderManager.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
    paramProviderManager.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
    paramProviderManager.addExtensionProvider("delay", "urn:xmpp:delay", new DelayInfoProvider());
    paramProviderManager.addExtensionProvider("ts", "urn:xmpp:timestamp", new q());
    paramProviderManager.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
    paramProviderManager.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
    ChatStateExtension.Provider localProvider = new ChatStateExtension.Provider();
    paramProviderManager.addExtensionProvider("active", "http://jabber.org/protocol/chatstates", localProvider);
    paramProviderManager.addExtensionProvider("composing", "http://jabber.org/protocol/chatstates", localProvider);
    paramProviderManager.addExtensionProvider("paused", "http://jabber.org/protocol/chatstates", localProvider);
    paramProviderManager.addExtensionProvider("inactive", "http://jabber.org/protocol/chatstates", localProvider);
    paramProviderManager.addExtensionProvider("gone", "http://jabber.org/protocol/chatstates", localProvider);
    paramProviderManager.addIQProvider("ping", "urn:xmpp:ping", com.easemob.chat.a.a.a.class);
    ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider());
    paramProviderManager.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());
    paramProviderManager.addIQProvider("query", "http://jabber.org/protocol/muc#admin", new MUCAdminProvider());
    paramProviderManager.addIQProvider("query", "http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());
    paramProviderManager.addExtensionProvider("x", "jabber:x:conference", new GroupChatInvitation.Provider());
    paramProviderManager.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
    paramProviderManager.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
    paramProviderManager.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
    paramProviderManager.addExtensionProvider("received", "urn:xmpp:receipts", new b());
  }

  private void resetAttempts()
  {
    this.attempts = 0;
    this.randomBase = -1;
  }

  private int timeDelay()
  {
    if (this.randomBase == -1)
      this.randomBase = (new Random().nextInt(5) + 5);
    this.attempts += 1;
    if ((this.attempts > 3) && (this.attempts <= 9))
      return this.randomBase + new Random().nextInt(5);
    if (this.attempts > 9)
    {
      if (this.randomBase * 3 > 30)
        return 25 + new Random().nextInt(5);
      return this.randomBase * 3;
    }
    return this.randomBase;
  }

  private synchronized void startReconnectionThread()
  {
    if (this.isDone)
      return;
    EMLog.d(TAG, hashCode() + " : enter startReconnectionThread()");
    if ((this.reconnectionThread != null) && (this.reconnectionThread.isAlive()))
      return;
    EMLog.d(TAG, "start reconnectionThread()");
    resetAttempts();
    this.reconnectionThread = new Thread()
    {
      public void run()
      {
        EMLog.d(XmppConnectionManager.TAG, "run in reconnectionThread");
        try
        {
          sleep(new Random().nextInt(2000));
        }
        catch (InterruptedException localInterruptedException1)
        {
          localInterruptedException1.printStackTrace();
          if (!XmppConnectionManager.this.isDone)
            break label188;
        }
        return;
        label188: 
        while ((!XmppConnectionManager.this.isConnected()) && (!XmppConnectionManager.this.isDone))
        {
          try
          {
            EMLog.d(XmppConnectionManager.TAG, "run in reconnectionThread with connection " + XmppConnectionManager.this.connection.hashCode());
            if (NetUtils.hasDataConnection(XmppConnectionManager.this.context))
              XmppConnectionManager.this.reconnectSync();
            else
              EMLog.d(XmppConnectionManager.TAG, "skip the reconnection since there is no data connection!");
          }
          catch (EaseMobException localEaseMobException)
          {
            localEaseMobException.printStackTrace();
          }
          int i = XmppConnectionManager.this.timeDelay();
          while ((!XmppConnectionManager.this.isConnected()) && (!XmppConnectionManager.this.isDone) && (i > 0))
          {
            try
            {
              sleep(1000L);
              i--;
              XmppConnectionManager.this.connectionListener.reconnectingIn(i);
            }
            catch (InterruptedException localInterruptedException2)
            {
              localInterruptedException2.printStackTrace();
              if (!XmppConnectionManager.this.isDone)
                break;
            }
            return;
          }
        }
      }
    };
    this.reconnectionThread.setName("EASEMOB Reconnection Thread");
    this.reconnectionThread.setDaemon(true);
    this.reconnectionThread.start();
  }

  private void onDisconnected()
  {
    EMLog.d(TAG, "on disconnected");
    if (this.wakeLock != null)
    {
      this.wakeLock.release();
      EMLog.d(TAG, "lock release");
    }
  }

  public static String getXmppResource(Context paramContext)
  {
    if (xmppResource == null)
      xmppResource = "mobile";
    return xmppResource;
  }

  public boolean isFinished()
  {
    return this.isDone;
  }

  void setBlackListActive()
    throws XMPPException
  {
    PrivacyListManager localPrivacyListManager = PrivacyListManager.getInstanceFor(this.connection);
    localPrivacyListManager.setActiveListName("special");
  }

  private void registerConnectivityReceiver()
  {
    if (this.context == null)
    {
      EMLog.e(TAG, "context is null!......");
      return;
    }
    if (this.isConnectivityRegistered)
      return;
    try
    {
      IntentFilter localIntentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
      EMLog.d(TAG, "register connectivity receiver.");
      this.context.registerReceiver(this.connectivityBroadcastReceiver, localIntentFilter);
      this.isConnectivityRegistered = true;
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  private void unregisterConnectivityReceiver()
  {
    if (this.context == null)
    {
      EMLog.e(TAG, "context is null!......");
      return;
    }
    EMLog.d(TAG, "unregisterConnectivityReceiver()");
    try
    {
      this.isConnectivityRegistered = false;
      this.context.unregisterReceiver(this.connectivityBroadcastReceiver);
    }
    catch (Exception localException)
    {
    }
  }

  private class PingListener
    implements PacketListener
  {
    private PingListener()
    {
    }

    public void processPacket(Packet paramPacket)
    {
      EMLog.d(XmppConnectionManager.TAG, "received ping packet from :" + paramPacket.getFrom());
      if (!(paramPacket instanceof com.easemob.chat.a.a.a))
        return;
      com.easemob.chat.a.a.a locala1 = (com.easemob.chat.a.a.a)paramPacket;
      if (locala1.getType() == IQ.Type.GET)
      {
        com.easemob.chat.a.a.a locala2 = new com.easemob.chat.a.a.a();
        locala2.setType(IQ.Type.RESULT);
        locala2.setTo(locala1.getFrom());
        locala2.setPacketID(locala1.getPacketID());
        XmppConnectionManager.this.connection.sendPacket(locala2);
      }
    }
  }

  private class XmppConnectionListener
    implements ConnectionListener
  {
    private XmppConnectionListener()
    {
    }

    public void connectionClosed()
    {
      EMLog.e(XmppConnectionManager.TAG, "connectionClosed");
      XmppConnectionManager.this.onDisconnected();
    }

    public void connectionClosedOnError(Exception paramException)
    {
      EMLog.e(XmppConnectionManager.TAG, "connectionClosedOnError in " + paramException);
      if ((paramException != null) && (paramException.getMessage() != null) && (paramException.getMessage().contains("conflict")))
      {
        EMLog.e(XmppConnectionManager.TAG, "connection closed caused by conflict. set autoreconnect to false");
      }
      else
      {
        XmppConnectionManager.this.registerConnectivityReceiver();
        XmppConnectionManager.this.startReconnectionThread();
      }
      XmppConnectionManager.this.onDisconnected();
      if (XmppConnectionManager.this.chatConnectionListener != null)
        XmppConnectionManager.this.chatConnectionListener.connectionClosedOnError(paramException);
    }

    public void reconnectingIn(int paramInt)
    {
      if (XmppConnectionManager.this.chatConnectionListener != null)
        XmppConnectionManager.this.chatConnectionListener.reconnectingIn(paramInt);
    }

    public void reconnectionFailed(Exception paramException)
    {
      EMLog.e(XmppConnectionManager.TAG, "xmpp con mgr reconnectionFailed:" + paramException);
      XmppConnectionManager.this.onDisconnected();
      if (XmppConnectionManager.this.chatConnectionListener != null)
        XmppConnectionManager.this.chatConnectionListener.reconnectionFailed(paramException);
    }

    public void reconnectionSuccessful()
    {
      EMLog.d(XmppConnectionManager.TAG, "reconnectionSuccessful");
      XmppConnectionManager.this.sendVersionIQ();
      EMLog.d(XmppConnectionManager.TAG, "send available presence after reconnected");
      Presence localPresence = new Presence(Presence.Type.available);
      XmppConnectionManager.this.connection.sendPacket(localPresence);
      if (XmppConnectionManager.this.chatConnectionListener != null)
        XmppConnectionManager.this.chatConnectionListener.reconnectionSuccessful();
    }
  }
}

/* Location:           D:\hygieia\userclient\common\libs\easemobchat_2.1.8.jar
 * Qualified Name:     com.easemob.chat.core.XmppConnectionManager
 * JD-Core Version:    0.6.1
 */